/**
 * 
 */
package org.alipay4j.component;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.alipay4j.Alipay;
import org.alipay4j.AlipayException;
import org.alipay4j.Configuration;
import org.alipay4j.http.AlipayHttpsClient;
import org.alipay4j.http.Response;
import org.alipay4j.model.base.Token;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 授权操作组件
 * @author 贺亮
 *
 */
public class BaseComponent extends AbstractComponent {

	public BaseComponent(Alipay alipay) {
		super(alipay);
	}
	
	/**
	 * 应用授权URL拼装
	 * @return 授权请求地址
	 * @throws org.alipay4j.AlipayException 支付宝操作异常
	 */
	public String getAppAuthUrl() throws AlipayException {
		if (StringUtils.isEmpty(alipay.getAppId())) {
            throw new IllegalArgumentException("appid can't be null or empty");
        }
		String url = "";
		//拼接URL
		@SuppressWarnings("deprecation")
		String param = "?app_id="+alipay.getAppId()+"&redirect_uri="+URLEncoder.encode(alipay.getAlipayConfig().getAppAuthUri());
		//判断是否为沙箱
		String gateway = alipay.getAlipayConfig().getAlipayGateway();
		if(gateway.indexOf("dev")!=-1) {
			url = "https://openauth.alipaydev.com/oauth2/appToAppAuth.htm";
		} else {
			url = "https://openauth.alipay.com/oauth2/appToAppAuth.htm";
		}
		return url+param;
	}
	
	/**
	 * 通过授权码换取token
	 * @param authCode 回调回传的授权码
	 * @return
	 */
	public Token appToken(String authCode) throws AlipayException {
		Map<String, String> body = new HashMap<String, String>();
		body.put("grant_type", "authorization_code");
		body.put("code", authCode);
		body.put("method", "alipay.open.auth.token.app");
		Response res = new AlipayHttpsClient(super.alipay).post(body);
        //根据请求结果判定，是否验证成功
  		JSONObject bodyRes = getObjRes(res, "alipay_system_oauth_token_response");
      	if (Configuration.isDebug()) {
              System.out.println("{alipay.open.auth.token.app}返回json：" + bodyRes.toString());
        }
        String codeRes = bodyRes.getString("code");
        if (codeRes != null) {
        	String sub_code = bodyRes.getString("sub_code");
          	String sub_msg = bodyRes.getString("sub_msg");
              //返回异常信息
              throw new AlipayException(getCause(sub_code,sub_msg));
        }
		return new Token(bodyRes);
	}
	
	
}
